package com.zdp.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.zdp.common.HeadHelper;
import com.zdp.feign.StockFeignClient;
import com.zdp.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sesshomaru
 * @date 2021/7/19
 */
@RestController
public class OrderController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StockFeignClient stockFeignClient;

    @Autowired
    private HeadHelper headHelper;

    @GetMapping("/order/create")
    public String createOrder(Integer productId, Integer userId) {
        // String reduceMsg = restTemplate.getForObject("http://stock-server/stock/reduce/" + productId, String.class);
        String reduceMsg = stockFeignClient.reduce(productId);
        return reduceMsg;
    }

    /**
     * 测试feign传递token
     * @param productId
     * @return
     */
    @PostMapping("/order/token")
    public String orderToken(@RequestParam Integer productId) {
        System.out.println("传入token: " + headHelper.getToken());
        return stockFeignClient.reduce(productId);
    }

    @GetMapping("/order/test")
    public String test() {
        return "test";
    }


    @GetMapping("/test-hot")
    @SentinelResource("hot")
    public String testHot(@RequestParam(required = false) String a, @RequestParam(required = false) String b) {
        return a + b;
    }

    @GetMapping("/order")
    public String getStock() {
        List<ServiceInstance> list = discoveryClient.getInstances("stock-server");
        String a="";
        for(ServiceInstance serviceInstance:list){
            a=a+" "+serviceInstance.getHost();
        }
        return a;
    }
}
